package com.gewu.pm.ui.activity.order;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gewu.pm.R;
import com.gewu.pm.aop.SingleClick;
import com.gewu.pm.app.AppActivity;
import com.gewu.pm.bean.GoodsBean;
import com.gewu.pm.other.GoodsDividerDecoration;
import com.gewu.pm.ui.adapter.order.GoodsAdapter;
import com.gewu.pm.ui.adapter.order.GoodsListAdapter;
import com.gewu.pm.ui.dialog.TipsTwoDialog;
import com.gewu.pm.utils.MathUtils;
import com.gewu.pm.utils.eventbus.EventBean;
import com.gewu.pm.utils.eventbus.EventCode;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 新增订单页面
 */
public final class NewOrderActivity extends AppActivity
        implements GoodsAdapter.OnQuantityChangeListener,
        GoodsAdapter.OnGoodsClickListener,
        GoodsListAdapter.OnFooterClickListener {

    private RelativeLayout mTerminalLayout;
    private TextView mTerminalNameView;
    private RecyclerView mGoodsRecyclerView;
    private TextView mTotalQuantityView;
    private TextView mTotalAmountView;
    private TextView mConfirmButton;

    private GoodsListAdapter mGoodsListAdapter;

    /** 商品列表 */
    private List<GoodsBean> mGoodsList = new ArrayList<>();

    public static void start(Context context) {
        Intent intent = new Intent(context, NewOrderActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_new_order;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mTerminalLayout = findViewById(R.id.rl_terminal);
        mTerminalNameView = findViewById(R.id.tv_terminal_name);
        mGoodsRecyclerView = findViewById(R.id.rv_goods);
        mTotalQuantityView = findViewById(R.id.tv_total_quantity);
        mTotalAmountView = findViewById(R.id.tv_total_amount);
        mConfirmButton = findViewById(R.id.btn_confirm);

        // 设置商品RecyclerView
        mGoodsRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mGoodsListAdapter = new GoodsListAdapter(this);
        mGoodsListAdapter.setOnQuantityChangeListener(this);
        mGoodsListAdapter.setOnGoodsClickListener(this);
        mGoodsListAdapter.setOnFooterClickListener(this);
        mGoodsRecyclerView.setAdapter(mGoodsListAdapter);
        
        // 添加分割线
        mGoodsRecyclerView.addItemDecoration(new GoodsDividerDecoration());

        // 设置点击监听
        setOnClickListener(mTerminalLayout,  mConfirmButton);
    }

    @Override
    protected void initData() {
        // TODO: 从Intent获取订单数据或加载草稿
        updateTotalInfo();
    }

    @Override
    protected boolean isRegisteredEventBus() {
        return true;  // 启用 EventBus
    }

    @Override
    protected void receiveEvent(EventBean event) {
        if (event.getCode() == EventCode.GOODS_SELECTED) {
            // 接收选中的商品
            Object data = event.getData();
            if (data instanceof List) {
                List<GoodsBean> selectedGoods = (List<GoodsBean>) data;
                
                // 添加到商品列表
                mGoodsList.addAll(selectedGoods);
                mGoodsListAdapter.setData(mGoodsList);
                
                // 更新合计
                updateTotalInfo();
                
                toast("已添加" + selectedGoods.size() + "种商品");
            }
        }
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.rl_terminal) {
            // 选择终端
            selectTerminal();
            
        } else if (viewId == R.id.btn_confirm) {
            // 确定提交订单
            onConfirmOrder();
        }
    }

    /**
     * 选择终端
     */
    private void selectTerminal() {
        // TODO: 打开选择终端对话框
        toast("选择终端");
    }

    /**
     * 确定提交订单（跳转到确认订单页面）
     */
    private void onConfirmOrder() {
        if (mGoodsList.isEmpty()) {
            toast("请添加商品");
            return;
        }

        // 获取当前的合计数量和金额
        String totalQuantityText = mTotalQuantityView.getText().toString()
            .replace(getString(R.string.total_quantity_unit), "");  // 去掉"合计数量:"
        
        // 提取金额数值
        String totalAmountText = mTotalAmountView.getText().toString()
            .replace("¥", "");  // 去掉"¥"符号
        
        double totalAmount = 0;
        try {
            totalAmount = Double.parseDouble(totalAmountText);
        } catch (NumberFormatException e) {
            // 解析失败使用0
        }

        // 跳转到确认订单页面
        ConfirmOrderActivity.start(this, totalQuantityText, totalAmount);
    }

    /**
     * 更新合计信息（数量和金额）
     */
    private void updateTotalInfo() {
        // 使用 LinkedHashMap 保持单位的出现顺序
        Map<String, Integer> unitMap = new LinkedHashMap<>();
        double totalAmount = 0;
        int totalQuantity = 0;

        for (GoodsBean goods : mGoodsList) {
            if (goods == null) continue;
            
            int quantity = goods.getQuantity();
            String unit = goods.getUnit();
            
            // 统计数量（按单位分组，保持出现顺序）
            if (unit != null && !unit.isEmpty() && quantity > 0) {
                unitMap.put(unit, unitMap.getOrDefault(unit, 0) + quantity);
            }
            
            totalQuantity += quantity;

            // 计算金额（使用 MathUtils.moneyXxx 方法确保金额精度）
            double price = parsePrice(goods.getPrice());
            double itemTotal = MathUtils.moneyMul(price, quantity);  // 金额乘法（保留2位）
            totalAmount = MathUtils.moneyAdd(totalAmount, itemTotal);  // 金额加法（保留2位）
        }

        // 拼接合计数量字符串："合计数量:3包4罐2瓶"（按照首次出现顺序）
        StringBuilder quantityText = new StringBuilder();
        if (unitMap.isEmpty()) {
            // 如果没有单位信息，显示总数
            if (totalQuantity > 0) {
                quantityText.append(totalQuantity);
            } else {
                quantityText.append("0");
            }
        } else {
            // 按单位分组显示（LinkedHashMap 保持插入顺序）
            for (Map.Entry<String, Integer> entry : unitMap.entrySet()) {
                quantityText.append(entry.getValue()).append(entry.getKey());
            }
        }
        mTotalQuantityView.setText(quantityText.toString());

        // 设置合计金额（不包含label，布局中已有"合计金额:"）
        // totalAmount 已经通过 moneyAdd 保留了2位小数
        String amountText = String.format("¥%.2f", totalAmount);
        mTotalAmountView.setText(amountText);
    }

    /**
     * 解析价格字符串
     */
    private double parsePrice(String priceStr) {
        if (priceStr == null || priceStr.isEmpty()) {
            return 0;
        }
        try {
            // 去除"¥"符号
            String numStr = priceStr.replace("¥", "").trim();
            return Double.parseDouble(numStr);
        } catch (NumberFormatException e) {
            return 0;
        }
    }

    // ========== GoodsAdapter 回调 ==========

    @Override
    public void onQuantityChanged() {
        updateTotalInfo();
    }

    @Override
    public void onStockInsufficient(String goodsName) {//库存不足
        toast(String.format(getString(R.string.stock_insufficient), goodsName));
    }

    @Override
    public void onDeleteGoods(int position) {//删除订单
        new TipsTwoDialog.Builder(getContext()).setTitle("您确定通过删除该商品吗").setListener(dialog -> {
            if (position >= 0 && position < mGoodsList.size()) {
                GoodsBean goods = mGoodsList.get(position);
                mGoodsList.remove(position);
                mGoodsListAdapter.setData(mGoodsList);
                // 重新计算合计
                updateTotalInfo();

            }
        }).show();
    }

    @Override
    public void onGoodsClick(int position) {
        // 点击商品，跳转到详情页
        if (position >= 0 && position < mGoodsList.size()) {
            GoodsBean goods = mGoodsList.get(position);
            GoodsDetailsActivity.start(this, goods.getId(), goods.getName());
        }
    }

    @Override
    public void onFooterClick() {
        // Footer 新增商品按钮点击
        AddGoodsActivity.start(this);
    }
}

